
/*
 *Gui Class
 *Authors : Kris Swanigan & Steven Gleason
 *Description : Creates a user interface for the user to access Google Calendars
 */
 
 alert("something different");
function displayCalendars(calendars) {
 	window.openDialog("chrome://googleconnection/content/calendarDialog.xul", "SelectCalendars","chrome,all,dependent",calendars);
}
function onLoad() {
}
function onUnload() {
	window.close();
}
function connect() {
	var username;
	var password;
	username = document.getElementById("googleusername").value;
	password = document.getElementById("googlepassword").value;
	authenticate(username, password);
	
}

function populateListBox(calendars) {
	var list = document.getElementById("calendarlist");
	var arrayLength = calendars.length;
	for (i = 0; i < arrayLength; i++) {
		list.appendItem(calendars[0][i], calendars[1][i]);
	}
}

function submitSelection() {
	var list = document.getElementById("calendarlist");
	var calendars = new Array();
	for(i = 0; i < list.selectedCount; i++) {
		calendars[i] = list.selectedItems[i].value;
	}
	//function: pass back calendar names
	window.close();
}


/*
 *Request Class
 Original Author: Josh Bohde
 *Contributor(s):
 *Description: Requests to the Google Server.
 *
 */
 
function output(string){ //FROZEN
	alert(string);
}

function browserSpecific(){ //FROZEN
	/*
	 *Original Author: Josh Bohde
	 *Contributor(s): 
	 *Description: Workaround for running code in browser, which does not want to do cross-domain calls.
	 */
  	try {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		output("Permissions allowed");
		} catch (e) {
		alert("Permission UniversalBrowserRead denied.");
		}
}

function authenticate(username, password){ //FROZEN
	/*
	 *Original Author: Josh Bohde
	 *Contributor(s): 
	 *Description: Sends the post request to Google to validate the username and password.
	 *Post: Sets the token. 
	 */
	output("Authenticating..."); 
	var params = "Email=" + username + "@gmail.com&Passwd=" + password + "&source=joshBohde-googleCalendarIntegration-version0.1&service=cl"; 
	var authReq = new XMLHttpRequest();
	authReq.open("POST", "https://www.google.com/accounts/ClientLogin", true); 

	//header stuff
	authReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	authReq.setRequestHeader("Content-length", params.length);
	authReq.setRequestHeader("Connection", "close");
	
	authReq.onreadystatechange = function(){
			try{
				if(authReq.readyState == 4){
					if (authReq.status == 200){
				      		var token = (authReq.responseText).split("Auth=")[1];
					}
			    		else if (authReq.status == 403){alert("Authentication failed!");}
						else
			  				alert("Error!");
				}	
			}catch(e){output("You probably logged in too much." + e)};
			if(token){request(token);}
			
			
	} 
	authReq.send(params);
}
	
function calendarListHandler(calendarList){ //TODO
	/*
	 * Original Author: Josh Bohde
	 * Contriubtor(s):
	 * Description: TODO 
	 * Returns:
	 */

//	# var title = node.getElementsByTagName('title').item(0).firstChild.data;  
//#   
//# content = '<div class="channeltitle">'+title+'</div>'; 
//var myElements = new Array();
//for(var x in newData.getElementsByTagName("name").item)
//{
//myElements[x] = newData.getElementsByTagName("name").item(x).innerText;
//document.write(myElements[x]);
//} 
//document.write(title.innerText);
//document.getElementsByTagName("id").innerHTML=newData.getElementsByTagName("id")[0].childNodes[0].nodeValue;
//alert((newData.getElementsByTagName("name").length).toString());
//for (i=0; i<=newData.getElementsByTagName("name").length-1; i++)
//{

//	var body=newData.getElementsByTagName("name").item(0);
//document.getElementsByTagName("name"+i).innerText=newData.getElementsByTagName("name")[i].childNodes[0].nodeValue;

//var names=body.getElementsByTagName("name");

//for(var i = 0; i < newData.length(); )document.write(names.item(0).innerHTML);

//}



}

function authenticatedRequest(type, token){ //TODO
	
	/*
	 * Original Author: Josh Bohde
	 * Contributor(s): Natalia Smirnova
	 * Description: Uses the token to access data that requires authentication.
	 * Prereqs: Authentication Token
	 * Returns: HTTP Request
	 */
	
	
	
	output("Authenticated Request called...");
	
	var dataReq=new XMLHttpRequest();
	var data = null;

	
	try{
		output("New Request Opened...");
		
		switch(type){
			case 1:
				try{
					
					dataReq.open("POST", "http://www.google.com/calendar/feeds/default/owncalendars/full" ,true);
					var parser = new DOMParser();
					data = parser.parseFromString("<entry xmlns='http://www.w3.org/2005/Atom'\n" + 
					   "xmlns:gd='http://schemas.google.com/g/2005'\n" +
					   "xmlns:gCal='http://schemas.google.com/gCal/2005'>\n" +
						"<title type='text'>This is an updated test calendar</title>\n" +
						"<summary type='text'>This calendar contains the practice schedule and game times.</summary>\n" +
						"<gCal:timezone value='America/Los_Angeles'></gCal:timezone>\n" +
						"<gCal:hidden value='false'></gCal:hidden>\n" +
						"<gCal:color value='#2952A3'></gCal:color>\n" +
						"<gd:where rel='' label='' valueString='Oakland'></gd:where>\n" +
						"</entry>", "text/xml");
					
					dataReq.setRequestHeader("Authorization", "GoogleLogin auth=" + token, true);
					dataReq.setRequestHeader("Content-type", "application/atom+xml");
					dataReq.setRequestHeader("Content-length", data.length);	
				}catch(e){output(e);}
				break;
			case 2:
				dataReq.open("GET","http://www.google.com/calendar/feeds/default/allcalendars/full" ,true,"username","password");
				dataReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				break;	
		}
		
		//header stuff
		
		
		
		//dataReq.setRequestHeader("Connection", "close");
		
	}catch(e){alert("authenticatedRequest error:" + e);}
	dataReq.onreadystatechange = function(){
		if(dataReq.readyState == 4)
		{
			switch(type){
				case 1:
					output(dataReq.status);
					break;
				case 2:
					try{
						if(dataReq.status == 200)
						{
							output("Request recieved");
							//res = XMLParse.xml2ObjArray(xml, 'Item'); 
							res=XMLParse.xml2ObjArray(dataReq.responseXML, 'title'); 
							//Document dt;
							
							/*var xmlDoc = document.implementation.createDocument("","",null);
							xmlDoc.load(dataReq.responseXML.data); 
							*/
							//var x;
							//for(x in dataReq.responseXML.documentElement.getElementsByTagName('title')){
								//output(dataReq.responseXML.documentElement.getElementsByTagName('title')[x].childNodes[x].nodeValue);
								//document.getElementsByTagName("id").innerHTML=newData.getElementsByTagName("id")[0].childNodes[0].nodeValue;
							//}
							//output(xmlDoc);
						}
					}catch(e){output("There was an error " + e);}
					break;
			}
		}	
	}
	output("State change function initialized.");
	output(dataReq);
	
	dataReq.send(data);
	
	output("Request sent");
}

function request(token){ //UNDER CONSTRUCTION
	/*
	 * Original Author: Josh Bohde
	 * Contributor(s):
	 * Description: Wrapper for authenticatedRequest for the list of calendars 
	 * Returns: List of Calendars in XML format.
	 */
	if(token){
		output(token);
		output("Requesting list of Calendars");
		
		var dataReq= new XMLHttpRequest();
		dataReq.open("GET","https://www.google.com/calendar/feeds/default/allcalendars/full" ,true);
		dataReq.setRequestHeader('Content-type','application/atom+xml');; 
		output("Stuff");
		try{
			dataReq.setRequestHeader("Authorization", "GoogleLogin auth=" + token); 
		}catch(e){alert(e);}
		output("Passed!");
		dataReq.setRequestHeader("Connection", "close");
		dataReq.onreadystatechange = function(){
			if(dataReq.readyState == 4){
				if(dataReq.status == 200){
					output("Request recieved");
					var xmlRawData = dataReq.responsXML
					var xmlCals = getMessage(xmlRawData);
					displayCalendars(xmlCals); 
					
				}
				else{
					output("Error: " + dataReq.status);
				}
			};
			
		}
		dataReq.send(null);
	}
}

/*
 *Original Author:
 *Contributor(s): Derin Phelps
 *Description: Loads the XML document into a variable
 */
function testXML(){
   alert("ahhhhhh");
   try{
      loadXML();
   } catch(e){output("Error in loadXML: " + e);}
}

function loadXML() {
   alert("AHHHHHH");
   var xmlDoc;
   xmlDoc=document.implementation.createDocument("","",null);
   xmlDoc.load("CalendarFeed.xml");
   xmlDoc.onload=getmessage(xmlDoc);
   var calendars = getmessage(xmlDoc); 
   displayCalendars(calendars); 
}

/*
  *Original Author:
  *Contributor(s): Derin Phelps, Steven Gleason
  *Description: Parses the XML document by tag names
 */
function getmessage(xmlDoc) {
   //This is supposed to parse out all of the <name> tags in an XML document.
   var calendars = new array();
   calendars[0] = new array();
   calendars[1] = new array();
   
   for (i=0; i<xmlDoc.getElementsByTagName("name").length; i++) {
      alert("length is " + xmlDoc.getElementsByTagName("name").length + " and i is " + i);
      calendars[0][i] = xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue;
      calendars[1][i] = xmlDoc.getElementsByTagName("id")[i].childNodes[0].nodeValue;
   }
   
   return calendars;
}
